package com.hj.collegetravel.services.impl;

import com.hj.collegetravel.dao.*;
import com.hj.collegetravel.models.*;
import com.hj.collegetravel.services.IAdminService;
import com.hj.collegetravel.tools.CookieUtils;
import com.hj.collegetravel.tools.DeleteFileUtil;
import com.hj.collegetravel.tools.GetIpAddr;
import com.ndktools.javamd5.Mademd5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import static org.apache.commons.lang.StringUtils.isNumeric;


@Service
public class AdminServiceImpl implements IAdminService {

	@Autowired
	CUserMapper userMapper;
	@Autowired
	CSchoolMapper schoolMapper;
	@Autowired
	CViewMapper viewMapper;
	@Autowired
	CPictureMapper pictureMapper;
	@Autowired
	CCommentMapper commentMapper;
	@Autowired
	CIndexMapper indexMapper;
	@Autowired
	CAdminMapper adminMapper;
	@Autowired
	CUpdateMapper updateMapper;


	SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");
	String path = this.getClass().getResource("/").getPath() + "static/images/";
	String pathPic = this.getClass().getResource("/").getPath() + "static/images/picture/";
	String pathUpdate = this.getClass().getResource("/").getPath() + "static/update/";


	/**
	 * 首页
	 */
	@Override
	public void index(HttpServletRequest request) {
		CAdmin cAdmin = (CAdmin) request.getSession().getAttribute("admin");
		cAdmin = adminMapper.selectByPrimaryKey(cAdmin.getaId());
		request.setAttribute("admin",cAdmin);
	}

	/**
	 * 获取用户列表
	 */
	@Override
	public List<CUser> getUsers(String id, String username, String email, Integer sex, HttpServletRequest request) {
		CUserExample cUserExample = new CUserExample();
		cUserExample.setOrderByClause("u_id desc");
		CUserExample.Criteria criteria = cUserExample.createCriteria();
		if (id!=null&&!id.equals("")&&isNumeric(id)){
			criteria.andUIdEqualTo(Integer.parseInt(id));
		}
		if (username!=null&&!username.equals(""))
			criteria.andUNameLike("%"+username+"%");
		if (email!=null&&!email.equals(""))
			criteria.andUEmailLike("%"+email+"%");
		if (sex!=null&&(sex.equals(1)||sex.equals(2)))
			criteria.andUSexEqualTo(sex);
		List<CUser> cUserList = userMapper.selectByExample(cUserExample);
		return cUserList;
	}

	/**
	 * 获取学校列表
	 */
	@Override
	public List<CSchool> getSchools(String id, String name, HttpServletRequest request) {
		CSchoolExample cSchoolExample = new CSchoolExample();
		cSchoolExample.setOrderByClause("s_id desc");
		CSchoolExample.Criteria criteria = cSchoolExample.createCriteria();
		if (id!=null&&!id.equals("")&&isNumeric(id)){
			criteria.andSIdEqualTo(Integer.parseInt(id));
		}
		if (name!=null&&!name.equals(""))
			criteria.andSNameLike("%"+name+"%");
		List<CSchool> cSchoolList = schoolMapper.selectByExampleWithBLOBs(cSchoolExample);
		return cSchoolList;
	}

    /**
     * 获取首页推荐列表
     */
    @Override
    public List<CIndex> getAds(String id, String desc, HttpServletRequest request) {
        CIndexExample example = new CIndexExample();
        example.setOrderByClause("i_id desc");
        CIndexExample.Criteria criteria = example.createCriteria();
        if (id!=null&&!id.equals("")&&isNumeric(id)){
            criteria.andIIdEqualTo(Integer.parseInt(id));
        }
        if (desc!=null&&!desc.equals(""))
            criteria.andIDescLike("%"+desc+"%");
        List<CIndex> list = indexMapper.selectByExample(example);
        return list;
    }

	/**
	 * 获取景点列表
	 */
	@Override
	public List<CView> getViews(String id, String name, Integer flag, Integer school, HttpServletRequest request) {
		CViewExample example = new CViewExample();
		example.setOrderByClause("v_id desc");
		CViewExample.Criteria criteria = example.createCriteria();
		if (id!=null&&!id.equals("")&&isNumeric(id)){
			criteria.andVIdEqualTo(Integer.parseInt(id));
		}
		if (name!=null&&!name.equals(""))
			criteria.andVNameLike("%"+name+"%");
		if (flag!=null&&!flag.equals(-1)){
			criteria.andVFlagEqualTo(flag);
		}
		if (school!=null&&!school.equals(0)){
			criteria.andVSidEqualTo(school);
		}
		List<CView> list = viewMapper.selectByExampleWithBLOBs(example);
		int i = 0;
		for (CView cView : list){
			CSchool cSchool = schoolMapper.selectByPrimaryKey(cView.getvSid());
			list.get(i).setSchoolname(cSchool.getsName());
			i++;
		}
		return list;
	}

	/**
	 * 获取管理员列表
	 */
	@Override
	public List<CAdmin> getRoles(String id, String name, String email, String phone, HttpServletRequest request) {
		CAdmin cAdmin = (CAdmin) request.getSession().getAttribute("admin");
		if (cAdmin==null||!cAdmin.getaId().equals(1))
			return null;
		CAdminExample example = new CAdminExample();
		example.setOrderByClause("a_id desc");
		CAdminExample.Criteria criteria = example.createCriteria();
		if (id!=null&&!id.equals("")&&isNumeric(id)){
			criteria.andAIdEqualTo(Integer.parseInt(id));
		}
		if (name!=null&&!name.equals(""))
			criteria.andAUsernameLike("%"+name+"%");
		if (email!=null&&!email.equals("")){
			criteria.andAEmailLike("%"+email+"%");
		}
		if (phone!=null&&!phone.equals("")){
			criteria.andAPhoneLike("%"+phone+"%");
		}
		criteria.andAIdNotEqualTo(1);
		List<CAdmin> list = adminMapper.selectByExample(example);
		return list;
	}

	/**
	 * 获取评论列表
	 */
	@Override
	public List<CComment> getComments(String id, Integer flag, Integer view, HttpServletRequest request) {
		CCommentExample example = new CCommentExample();
		example.setOrderByClause("c_id desc");
		CCommentExample.Criteria criteria = example.createCriteria();
		if (id!=null&&!id.equals("")&&isNumeric(id)){
			criteria.andCIdEqualTo(Integer.parseInt(id));
		}
		if (flag!=null&&!flag.equals(-1)){
			if (flag.equals(0))
				criteria.andCFlagEqualTo(0);
			else
				criteria.andCFlagNotEqualTo(0);
		}
		if (view!=null&&!view.equals(0)){
			criteria.andCVidEqualTo(view);
		}
		List<CComment> list = commentMapper.selectByExampleWithBLOBs(example);
		int i = 0;
		for(CComment comment : list){
			list.get(i).setcContent(comment.getcContent().replace("images/comment","/images/comment"));
			CUser cUser = userMapper.selectByPrimaryKey(comment.getcUid());
			if (cUser!=null){
				list.get(i).setUname(cUser.getuName());
				list.get(i).setUicon(cUser.getuPic());
			}
			int uid = comment.getcFlag();
			if (comment.getcFlag().equals(100)){
				uid = commentMapper.selectByPrimaryKey(comment.getcCid()).getcUid();
			}
			cUser = userMapper.selectByPrimaryKey(uid);
			if (cUser!=null){
				list.get(i).setUname2(cUser.getuName());
				list.get(i).setUicon2(cUser.getuPic());
			}
			CView cView = viewMapper.selectByPrimaryKey(comment.getcVid());
			list.get(i).setVname(cView.getvName());
			i++;
		}
		return list;
	}

	/**
	 * 图片管理
	 */
	@Override
	public List<CPicture> getPictures(Integer id, Integer flag, HttpServletRequest request) {
		if (flag==null)
			flag = 0;
		if (flag.equals(0)||id==null)
			id = 0;
		CPictureExample example = new CPictureExample();
		CPictureExample.Criteria criteria = example.createCriteria();
		if (!flag.equals(0)){
			criteria.andPFlagEqualTo(flag);
		}
		if (!id.equals(0)){
			criteria.andPVsidEqualTo(id);
		}
		example.setOrderByClause("p_id desc");
		List<CPicture> list = pictureMapper.selectByExample(example);
		int i=0;
		for (CPicture cPicture : list){
			String alt = "";
			if (cPicture.getpFlag().equals(1)){
				CView cView = viewMapper.selectByPrimaryKey(cPicture.getpVsid());
				alt = "[景点] " + cView.getvName();
			}
			else if (cPicture.getpFlag().equals(2)){
				CSchool cSchool = schoolMapper.selectByPrimaryKey(cPicture.getpVsid());
				alt = "[地图] " + cSchool.getsName();
			}
			else {
				CComment cComment = commentMapper.selectByPrimaryKey(cPicture.getpVsid());
				alt = "[评论] 用户id"+cComment.getcUid();
			}
			list.get(i).setAlt(alt);
			i++;
		}
		return list;
	}

	/**
	 * app更新
	 */
	@Override
	public List<CUpdate> getUpdates(Integer id, Integer flag, HttpServletRequest request) {
		CUpdateExample updateExample = new CUpdateExample();
		updateExample.setOrderByClause("u_id desc");
		List<CUpdate> updateList = updateMapper.selectByExample(updateExample);
		return updateList;
	}

	/**
	 * 登录
	 * @param login 用户名
	 * @param pwd 密码
	 */
	@Override
	public boolean dologin(String login, String pwd, HttpServletRequest request) {
		Mademd5 mademd5 = new Mademd5();
		String password = mademd5.toMd5(pwd);
		CAdminExample adminExample = new CAdminExample();
		adminExample.or().andAUsernameEqualTo(login).andAPasswordEqualTo(password);
		List<CAdmin> adminList = adminMapper.selectByExample(adminExample);
		if (adminList.size()>0){
			adminList.get(0).setaRecent(new Date());
			adminList.get(0).setaIp(GetIpAddr.getIpAddr(request));
			adminMapper.updateByPrimaryKey(adminList.get(0));//更新ip+登录时间

			HttpSession session = request.getSession(true);
			session.setAttribute("admin", adminList.get(0)); //放入Session

			CookieUtils.addCookie("admin_login", login);//用户名cookies
		}
		return adminList.size()>0;
	}

	/**
	 * 验证密码
	 */
	@Override
	public boolean checkpass(String pass, HttpServletRequest request) {
		CAdmin admin = (CAdmin) request.getSession().getAttribute("admin");
		pass = new Mademd5().toMd5(pass);
		if (admin.getaPassword().equals(pass)){
			return true;
		}
		else
			return false;
	}

	/**
	 * 添加用户·post
	 */
	@Override
	public boolean addUser(CUser user, HttpServletRequest request) {
		Mademd5 mademd5 = new Mademd5();
		String password = mademd5.toMd5(user.getuPassword());
		user.setuPassword(password);
		user.setuRegtime(new Date());
		user.setuPic("user.png");//默认头像
		user.setuIp(GetIpAddr.getIpAddr(request));
		return userMapper.insert(user)>0;
	}

	/**
	 * 编辑用户·get
	 */
	@Override
	public void userEdit(Integer uId, HttpServletRequest request) {
		CUser cUser = userMapper.selectByPrimaryKey(uId);
		if (cUser.getuLogintime()!=null)
			cUser.setuIp(df2.format(cUser.getuLogintime()));
		else
			cUser.setuIp("");
		request.setAttribute("user",cUser);
	}

	/**
	 * 编辑用户·post
	 */
	@Override
	public boolean editUser(CUser cUser, HttpServletRequest request) {
		CUser user = userMapper.selectByPrimaryKey(cUser.getuId());
		cUser.setuIp(user.getuIp());
		cUser.setuPassword(user.getuPassword());
		cUser.setuRegtime(user.getuRegtime());
		cUser.setuLogintime(user.getuLogintime());
		return userMapper.updateByPrimaryKey(cUser)>0;
	}

	/**
	 * 删除用户
	 */
	@Override
	public boolean delUser(Integer[] ids, HttpServletRequest request) {
		for (Integer id : ids){
			//删除评论
			CCommentExample cCommentExample = new CCommentExample();
			cCommentExample.or().andCUidEqualTo(id);
			commentMapper.deleteByExample(cCommentExample);
			CUser cUser = userMapper.selectByPrimaryKey(id);
			if (cUser==null)
				continue;
			//删除头像文件
			if (!cUser.getuPic().equals("user.png")){
				DeleteFileUtil.deleteFile(path + "headicon/" + cUser.getuPic());
			}
			else{
				System.out.println("-------==默认头像，不删除==---------");
			}
			userMapper.deleteByPrimaryKey(id);
		}
		return true;
	}

	/**
	 * 图片上传
	 */
	@Override
	public boolean uploadpic(String file, HttpServletRequest request) {
		CAdmin admin = (CAdmin) request.getSession().getAttribute("admin");
		Base64.Decoder decoder = Base64.getDecoder();
		// 去掉base64编码的头部 如："data:image/jpeg;base64," 如果不去，转换的图片不可以查看
		file = file.substring(23);
		//解码
		byte[] imgByte = decoder.decode(file);
		String iconPath = this.getClass().getResource("/").getPath() + "static/images/picture/";//图片目录
		String fileName = "picture_" +admin.getaId() +  ".jpg";//头像名
		try {
			FileOutputStream out = new FileOutputStream(iconPath+fileName); // 输出文件路径
			out.write(imgByte);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		request.setAttribute("src",fileName);
		return true;
	}

	/**
	 * 添加学校
	 */
	@Override
	public boolean addSchool(CSchool cSchool, HttpServletRequest request) {
		String filename = "picture_"+System.currentTimeMillis() + ".jpg";
		File file = new File(path+"picture/"+cSchool.getsPic());
		file.renameTo(new File(path+"picture/"+filename));
		cSchool.setsPic(filename);
		return schoolMapper.insert(cSchool)>0;
	}

    /**
     * 更换学校图片
     */
    @Override
    public boolean eSchoolPic(String file, Integer id, HttpServletRequest request) {
        CSchool cSchool = schoolMapper.selectByPrimaryKey(id);
        if (cSchool==null)
            return false;
        Base64.Decoder decoder = Base64.getDecoder();
        // 去掉base64编码的头部 如："data:image/jpeg;base64," 如果不去，转换的图片不可以查看
        file = file.substring(23);
        //解码
        byte[] imgByte = decoder.decode(file);
        String iconPath = this.getClass().getResource("/").getPath() + "static/images/picture/";//图片目录
        String fileName = "SchoolPicture_" +id +"_"+System.currentTimeMillis()+".jpg";//文件名
        try {
            FileOutputStream out = new FileOutputStream(iconPath+fileName); // 输出文件路径
            out.write(imgByte);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (!fileName.equals(cSchool.getsPic()))
            DeleteFileUtil.deleteFile(iconPath+cSchool.getsPic());
        cSchool.setsPic(fileName);
        schoolMapper.updateByPrimaryKey(cSchool);
        request.setAttribute("src",fileName);
        return true;
    }

    /**
     * 编辑学校·get
     */
    @Override
    public void schoolEdit(Integer sId, HttpServletRequest request) {
        CSchool cSchool = schoolMapper.selectByPrimaryKey(sId);
        request.setAttribute("school",cSchool);
    }

    /**
     * 编辑学校·post
     */
    @Override
    public boolean editSchool(CSchool cSchool, HttpServletRequest request) {
        CSchool cSchool2 = schoolMapper.selectByPrimaryKey(cSchool.getsId());
        if (!cSchool2.getsPic().equals(cSchool.getsPic()))
            DeleteFileUtil.deleteFile(pathPic+cSchool2.getsPic());
        return schoolMapper.updateByPrimaryKeyWithBLOBs(cSchool)>0;
    }

    /**
     * 删除学校
     */
    @Override
    public boolean delSchool(Integer[] ids, HttpServletRequest request) {
        for (Integer id : ids){
            CSchool cSchool = schoolMapper.selectByPrimaryKey(id);
            if (cSchool==null)
                return false;
            //删除学校地图
            CPictureExample cPictureExample = new CPictureExample();
            cPictureExample.or().andPFlagEqualTo(2).andPVsidEqualTo(id);
            List<CPicture> cPictureList = pictureMapper.selectByExample(cPictureExample);
            for (CPicture cPicture : cPictureList){
                DeleteFileUtil.deleteFile(pathPic+cPicture.getpFilename());//删除文件
                pictureMapper.deleteByPrimaryKey(cPicture.getpId());//删除数据库
            }
            //删除景点
            CViewExample cViewExample = new CViewExample();
            cViewExample.or().andVSidEqualTo(id);
            List<CView> cViewList = viewMapper.selectByExample(cViewExample);
            for (CView cView : cViewList){
                //删除景点图片
                cPictureExample.clear();
                cPictureExample.or().andPFlagEqualTo(1).andPVsidEqualTo(cView.getvId());
                cPictureList = pictureMapper.selectByExample(cPictureExample);
                for (CPicture cPicture : cPictureList){
                    DeleteFileUtil.deleteFile(pathPic+cPicture.getpFilename());//删除文件
                    pictureMapper.deleteByPrimaryKey(cPicture.getpId());//删除数据库
                }
                //删除景点评论
                CCommentExample cCommentExample = new CCommentExample();
                cCommentExample.or().andCVidEqualTo(cView.getvId());
                commentMapper.deleteByExample(cCommentExample);

                viewMapper.deleteByPrimaryKey(cView.getvId());//删除景点
            }
            //删除学校图片
            DeleteFileUtil.deleteFile(pathPic+cSchool.getsPic());
            //删除学校
            schoolMapper.deleteByPrimaryKey(id);

        }
        return true;
    }

    /**
     * 添加推荐
     */
    @Override
    public boolean addAds(CIndex cIndex, HttpServletRequest request) {
        String filename = "picture_"+System.currentTimeMillis() + ".jpg";
        File file = new File(path+"picture/"+cIndex.getiPic());
        file.renameTo(new File(path+"picture/"+filename));
        cIndex.setiPic(filename);
        cIndex.setiTime(new Date());
        return indexMapper.insert(cIndex)>0;
    }

    /**
     * 编辑推荐·get
     */
    @Override
    public void adsEdit(Integer iId, HttpServletRequest request) {
        CIndex cIndex = indexMapper.selectByPrimaryKey(iId);
        request.setAttribute("ad",cIndex);
    }

    /**
     * 更换推荐图片
     */
    @Override
    public boolean eAdPic(String file, Integer id, HttpServletRequest request) {
        CIndex cIndex = indexMapper.selectByPrimaryKey(id);
        if (cIndex==null)
            return false;
        Base64.Decoder decoder = Base64.getDecoder();
        // 去掉base64编码的头部 如："data:image/jpeg;base64," 如果不去，转换的图片不可以查看
        file = file.substring(23);
        //解码
        byte[] imgByte = decoder.decode(file);
        String iconPath = this.getClass().getResource("/").getPath() + "static/images/picture/";//图片目录
        String fileName = "IndexPicture_" +id +"_"+System.currentTimeMillis()+".jpg";//文件名
        try {
            FileOutputStream out = new FileOutputStream(iconPath+fileName); // 输出文件路径
            out.write(imgByte);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if (!fileName.equals(cIndex.getiPic()))
            DeleteFileUtil.deleteFile(iconPath+cIndex.getiPic());
        cIndex.setiPic(fileName);
        indexMapper.updateByPrimaryKey(cIndex);
        request.setAttribute("src",fileName);
        return true;
    }

    /**
     * 编辑推荐·post
     */
    @Override
    public boolean editAds(CIndex cIndex, HttpServletRequest request) {
        CIndex cIndex2 = indexMapper.selectByPrimaryKey(cIndex.getiId());
        if (!cIndex2.getiPic().equals(cIndex.getiPic()))
            DeleteFileUtil.deleteFile(pathPic+cIndex2.getiPic());
        return indexMapper.updateByPrimaryKey(cIndex)>0;
    }

    /**
     * 删除推荐
     */
    @Override
    public boolean delAds(Integer[] ids, HttpServletRequest request) {
        for (Integer id : ids){
            CIndex cIndex = indexMapper.selectByPrimaryKey(id);
            if (cIndex==null)
                continue;
            //删除图片文件
            DeleteFileUtil.deleteFile(pathPic+cIndex.getiPic());
            indexMapper.deleteByPrimaryKey(id);
        }
        return true;
    }

	/**
	 * 景点管理/添加景点·get
	 */
	@Override
	public void views(HttpServletRequest request) {
		List<CSchool> cSchoolList = schoolMapper.selectByExample(new CSchoolExample());
		request.setAttribute("cSchoolList",cSchoolList);
	}

	/**
	 * 添加景点·post
	 */
	@Override
	public boolean addView(CView cView, HttpServletRequest request) {
		cView.setvHot(0);
		return viewMapper.insert(cView)>0;
	}

	/**
	 * 编辑景点·get
	 */
	@Override
	public void viewEdit(Integer vId, HttpServletRequest request) {
		views(request);
		CView cView = viewMapper.selectByPrimaryKey(vId);
		request.setAttribute("view",cView);
	}

	/**
	 * 编辑景点·post
	 */
	@Override
	public boolean editView(CView cView, HttpServletRequest request) {
		return viewMapper.updateByPrimaryKeyWithBLOBs(cView)>0;
	}

	/**
	 * 删除景点
	 */
	@Override
	public boolean delView(Integer[] ids, HttpServletRequest request) {
		for (Integer id : ids){
			CView cView = viewMapper.selectByPrimaryKey(id);
			if (cView==null)
				continue;
			//删除图片文件
			CPictureExample cPictureExample = new CPictureExample();
			cPictureExample.or().andPFlagEqualTo(1).andPVsidEqualTo(cView.getvId());
			List<CPicture> cPictureList = pictureMapper.selectByExample(cPictureExample);
			for (CPicture cPicture : cPictureList){
				DeleteFileUtil.deleteFile(pathPic+cPicture.getpFilename());//删除文件
				pictureMapper.deleteByPrimaryKey(cPicture.getpId());//删除数据库
			}
			//删除景点评论
			CCommentExample cCommentExample = new CCommentExample();
			cCommentExample.or().andCVidEqualTo(cView.getvId());
			commentMapper.deleteByExample(cCommentExample);

			viewMapper.deleteByPrimaryKey(id);//删除景点
		}
		return true;
	}

	/**
	 * 添加管理员
	 */
	@Override
	public boolean addRole(CAdmin cAdmin, HttpServletRequest request) {
		CAdmin cAdmin1 = (CAdmin) request.getSession().getAttribute("admin");
		if (cAdmin1==null||!cAdmin1.getaId().equals(1))
			return false;
		cAdmin.setaPassword(new Mademd5().toMd5(cAdmin.getaPassword()));
		return adminMapper.insert(cAdmin)>0;
	}

	/**
	 * 编辑管理员·get
	 */
	@Override
	public void roleEdit(Integer aId, HttpServletRequest request) {
		CAdmin cAdmin1 = (CAdmin) request.getSession().getAttribute("admin");
		if (cAdmin1==null||!cAdmin1.getaId().equals(1))
			return;
		cAdmin1 = adminMapper.selectByPrimaryKey(aId);
		request.setAttribute("admin",cAdmin1);
	}

	/**
	 * 编辑管理员·post
	 */
	@Override
	public boolean editRole(CAdmin cAdmin, HttpServletRequest request) {
		CAdmin cAdmin1 = (CAdmin) request.getSession().getAttribute("admin");
		if (cAdmin1==null||!cAdmin1.getaId().equals(1))
			return false;
		return adminMapper.updateByPrimaryKeySelective(cAdmin)>0;
	}

	/**
	 * 删除管理员
	 */
	@Override
	public boolean delRole(Integer[] ids, HttpServletRequest request) {
		CAdmin cAdmin1 = (CAdmin) request.getSession().getAttribute("admin");
		if (cAdmin1==null||!cAdmin1.getaId().equals(1))
			return false;
		for (Integer id : ids){
			if (id.equals(1))
				continue;
			adminMapper.deleteByPrimaryKey(id);
		}
		return true;
	}

	/**
	 * 评论管理
	 */
	@Override
	public void comments(HttpServletRequest request) {
		List<CView> cViewList = viewMapper.selectByExample(new CViewExample());
		request.setAttribute("cViewList",cViewList);
	}

	/**
	 * 删除评论
	 */
	@Override
	public boolean delComment(Integer[] ids, HttpServletRequest request) {
		for(Integer id : ids){
			CComment cComment = commentMapper.selectByPrimaryKey(id);
			if (cComment!=null){
				List<Integer> cIds = new ArrayList<>();
				cIds.add(cComment.getcId());
				if (cComment.getcFlag().equals(0)){
					//获取子评论
					CCommentExample cCommentExample = new CCommentExample();
					cCommentExample.or().andCFlagNotEqualTo(0).andCCidEqualTo(cComment.getcId());
					List<CComment> cCommentList = commentMapper.selectByExample(cCommentExample);
					for (CComment cComment1 : cCommentList){
						cIds.add(cComment1.getcId());
					}
				}
				//删除图片
				CPictureExample cPictureExample = new CPictureExample();
				cPictureExample.or().andPVsidIn(cIds).andPFlagEqualTo(3);
				List<CPicture> pictureList = pictureMapper.selectByExample(cPictureExample);
				for (CPicture cPicture : pictureList){
					//删除文件
					DeleteFileUtil.deleteFile(pathPic+cPicture.getpFilename());
					//删除数据库
					pictureMapper.deleteByPrimaryKey(cPicture.getpId());
				}
				//删除评论
				CCommentExample cCommentExample = new CCommentExample();
				cCommentExample.or().andCFlagNotEqualTo(0).andCCidEqualTo(cComment.getcId());
				cCommentExample.or().andCIdEqualTo(id);
				commentMapper.deleteByExample(cCommentExample);
			}
		}
		return true;
	}

	/**
	 * 图片管理/添加图片·get
	 */
	@Override
	public void pictures(Integer flag, Integer id, HttpServletRequest request) {
		if (flag==null)
			flag = 0;
		if (flag.equals(0)||id==null)
			id = 0;
		if (flag.equals(1)){
			List<CView> viewList = viewMapper.selectByExample(new CViewExample());
			request.setAttribute("list",viewList);
		}
		else if (flag.equals(2)){
			List<CSchool> schoolList = schoolMapper.selectByExample(new CSchoolExample());
			request.setAttribute("list",schoolList);
		}
		request.setAttribute("flag",flag);
		request.setAttribute("id",id);
	}

	/**
	 * 添加图片·post
	 */
	@Override
	public boolean addPicture(CPicture cPicture, HttpServletRequest request) {
		String filename = "picture_"+System.currentTimeMillis() + ".jpg";
		File file = new File(path+"picture/"+cPicture.getpFilename());
		file.renameTo(new File(path+"picture/"+filename));
		cPicture.setpFilename(filename);
		cPicture.setpTime(new Date());
		return pictureMapper.insert(cPicture)>0;
	}

	/**
	 * 删除图片
	 */
	@Override
	public boolean delPicture(Integer[] ids, HttpServletRequest request) {
		for (Integer id : ids){
			CPicture picture = pictureMapper.selectByPrimaryKey(id);
			if (picture!=null){
				DeleteFileUtil.deleteFile(pathPic+picture.getpFilename());
				pictureMapper.deleteByPrimaryKey(id);
			}
		}
		return true;
	}

	/**
	 * 修改资料
	 */
	@Override
	public boolean setInfo(CAdmin cAdmin, HttpServletRequest request) {
		CAdmin cAdmin1 = (CAdmin) request.getSession().getAttribute("admin");
		cAdmin1 = adminMapper.selectByPrimaryKey(cAdmin1.getaId());
		cAdmin1.setaUsername(cAdmin.getaUsername());
		cAdmin1.setaPhone(cAdmin.getaPhone());
		cAdmin1.setaEmail(cAdmin.getaEmail());
		return adminMapper.updateByPrimaryKeySelective(cAdmin1)>0;
	}

	/**
	 * 修改密码
	 */
	@Override
	public Integer setPassword(String oldPassword, String password, HttpServletRequest request) {
		Mademd5 mademd5 = new Mademd5();
		oldPassword = mademd5.toMd5(oldPassword);
		password = mademd5.toMd5(password);
		CAdmin cAdmin1 = (CAdmin) request.getSession().getAttribute("admin");
		cAdmin1 = adminMapper.selectByPrimaryKey(cAdmin1.getaId());
		if (cAdmin1.getaPassword().equals(oldPassword)){
			cAdmin1.setaPassword(password);
			return adminMapper.updateByPrimaryKeySelective(cAdmin1);
		}
		return -1;
	}

	/**
	 * 发布更新
	 */
	@Override
	public Integer addUpdate(MultipartFile file, CUpdate update, HttpServletRequest request) {
		if (!file.isEmpty()) {
			StringBuffer url = request.getRequestURL();
			String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
			String s = String.valueOf(System.currentTimeMillis()).substring(8);
			String name = file.getOriginalFilename();//获取接受到的文件名称
			String suffix = name.substring(name.lastIndexOf(".") + 1);//后缀名
			if (suffix.trim().toLowerCase().equals("apk")) {
				name = "CollegeTravel_v"+update.getuVersion()+"_"+ s +"."+ suffix;
				System.out.println("==============> 附件：" + name);
				File fi = new File(pathUpdate, name);       //将path路径与文件名称联系在一起
				try {
					file.transferTo(fi);                   //上传文件
				} catch (IOException e) {
					e.printStackTrace();
				}
				update.setuDownload(tempContextUrl+"update/"+name);                //附件名->数据库

				update.setuTime(new Date());
				return updateMapper.insert(update);
			}
			else
				return -3;//附件格式不正确
		} else
			return -1;//附件为空
	}

	/**
	 * 编辑更新·post
	 */
	@Override
	public boolean editUpdate(CUpdate update, HttpServletRequest request) {
		return updateMapper.updateByPrimaryKeySelective(update)>0;
	}

	/**
	 * 编辑更新·get
	 */
	@Override
	public void updateEdit(Integer uId, HttpServletRequest request) {
		CUpdate update = updateMapper.selectByPrimaryKey(uId);
		request.setAttribute("update",update);
	}

	/**
	 * 删除更新
	 */
	@Override
	public boolean delUpdate(Integer[] ids, HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
		for (Integer id : ids){
			CUpdate update = updateMapper.selectByPrimaryKey(id);
			if (update!=null){
				String app = update.getuDownload();
				app = app.replace(tempContextUrl+"update/","");
				//删除文件
				DeleteFileUtil.deleteFile(pathUpdate+app);
				updateMapper.deleteByPrimaryKey(id);
			}
		}
		return true;
	}


}
